package com.haidao.admin.component.service.thirdpart.impl;

import cn.com.jit.ida.util.pki.encoders.Base64;
import cn.com.jit.new_vstk.AdvanceSignClient;
import cn.com.jit.new_vstk.Bean.SymmKeyNo;
import cn.com.jit.new_vstk.Bean.SymmKeyParams;
import cn.com.jit.new_vstk.exception.NewCSSException;
import com.haidao.admin.component.configuration.properties.CssConfigProperties;
import com.haidao.admin.component.service.thirdpart.CryptoService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 三类区加解密服务类
 */
@Service
@Slf4j
public class ThirdAreaCryptoServiceImpl implements CryptoService {
    @Resource
    private CssConfigProperties cssConfigProperties;

    // 3.1.18
    @Override
    public String encrypt(String str) {
        String symmNo = "cmac.00000";//服务器密钥编号
        try {
            //如果找不到类路径下的cssconfig.properties文件，请写绝对路径
            AdvanceSignClient client = new AdvanceSignClient(cssConfigProperties.getConfig());

            SymmKeyParams symmParams  = new SymmKeyNo(symmNo);

            //对称加密
            byte[] endata = client.symmEncrypt(symmParams, str.getBytes());

            log.info("加密成功");
            String base64Str = new String(Base64.encode(endata));
            log.info("base64的对称加密结果为：" + base64Str);
            return base64Str;
        } catch (NewCSSException e) {
            log.info("加密失败");
            log.info("错误号为：" + e.getCode());
            log.info("错误描述为: " + e.getDescription());
            log.info("日志标识码: " + e.getSerialNumber());
        }
        throw new RuntimeException("加密失败");
    }

    // 3.1.19
    @Override
    public String decrypt(String encoded) {
        String symmNo = "cmac.00000";//服务器密钥编号
        try {
            //如果找不到类路径下的cssconfig.properties文件，请写绝对路径
            AdvanceSignClient client = new AdvanceSignClient("cssconfig.properties");

            SymmKeyParams symmParams = new SymmKeyNo(symmNo);

            //非base64的对称加密结果
            byte[] encData = Base64.decode(encoded);
            //对称解密
            byte[] plainData = client.symmDecrypt(symmParams, encData);

            log.info("解密成功");
            log.info("解密后的原文为：" + new String(plainData));
            return new String(plainData);
        } catch (NewCSSException e) {
            log.info("解密失败");
            log.info("错误号为：" + e.getCode());
            log.info("错误描述为: " + e.getDescription());
            log.info("日志标识码: " + e.getSerialNumber());
        }
        throw new RuntimeException("解密失败");
    }
}
